package top.xana.acg.common.base.ui

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.annotation.IdRes
import androidx.annotation.LayoutRes
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.navigation.Navigation
import top.xana.acg.common.utils.navTo

/**
 * Created by xana on 2022/1/7
 * Describe: hello world
 */
abstract class BaseFragment : Fragment() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initArg(savedInstanceState)
    }



    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        init()
    }


    protected var rootView: View? = null

    final override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        if (null == rootView) {
            rootView = layoutInflater.inflate(getLayoutId(), container, false)
        }
        return rootView
    }

    private var firstInit = true

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        if(firstInit){
            initView()
            firstInit = false
        }
    }

    @JvmName("getBinding1")
    protected fun <T : ViewDataBinding> getBinding() =
        DataBindingUtil.bind<T>(rootView!!)!!

    @LayoutRes
    abstract fun getLayoutId(): Int

    open fun init() {}
    open fun initView() {}
    open fun initData() {}
    open fun toast(msg: String) = Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()

    open fun initArg(bundle: Bundle?){

    }


    open fun navTo(@IdRes id: Int) = requireView().navTo(id)

    fun <T : View> getView(@IdRes id: Int) = requireView().findViewById<T>(id)


}